package com.example.aicodehelper.ai.store;

import com.example.aicodehelper.entity.ChatMemoryEntity;
import com.example.aicodehelper.repository.ChatMemoryRepository;
import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.ChatMessageDeserializer;
import dev.langchain4j.data.message.ChatMessageSerializer;
import dev.langchain4j.store.memory.chat.ChatMemoryStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


import java.util.List;
import java.util.Optional;

// 假设已定义数据库实体类ChatMemoryEntity和对应的Repository
@Component
public class PersistentChatMemoryStore implements ChatMemoryStore {

    @Autowired
    private ChatMemoryRepository chatMemoryRepository; // 数据库操作接口

    @Override
    public List<ChatMessage> getMessages(Object memoryId) {
        // 1. 将memoryId转为字符串（如用户ID/会话ID）
        String id = memoryId.toString();
        // 2. 从数据库查询
        Optional<ChatMemoryEntity> entity = chatMemoryRepository.findByMemoryId(id);
        // 3. 反序列化为ChatMessage列表（无数据则返回空列表）
        return entity.map(e -> ChatMessageDeserializer.messagesFromJson(e.getMessagesJson()))
                .orElse(List.of());
    }

    @Override
    public void updateMessages(Object memoryId, List<ChatMessage> messages) {
        // 1. 序列化消息列表为JSON
        String messagesJson = ChatMessageSerializer.messagesToJson(messages);
        // 2. 保存到数据库（存在则更新，不存在则插入）
        ChatMemoryEntity entity = new ChatMemoryEntity();
        entity.setMemoryId(memoryId.toString());
        entity.setMessagesJson(messagesJson);
        chatMemoryRepository.save(entity);
    }

    @Override
    public void deleteMessages(Object memoryId) {
        // 从数据库删除对应记录
        chatMemoryRepository.deleteById(memoryId.toString());
    }
}